package com.atguigu.jxc.service.impl;

import com.atguigu.jxc.dao.CustomerDao;
import com.atguigu.jxc.dao.UserDao;
import com.atguigu.jxc.domain.ErrorCode;
import com.atguigu.jxc.domain.ServiceVO;
import com.atguigu.jxc.domain.SuccessCode;
import com.atguigu.jxc.entity.Customer;
import com.atguigu.jxc.entity.Log;
import com.atguigu.jxc.service.CustomerService;
import com.atguigu.jxc.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author :ttm
 * @description :
 */
@Service
public class CustomerServiceImpl implements CustomerService {
    @Autowired
    private CustomerDao customerDao;
    @Autowired
    private LogService logService;

    @Override
    public Map<String, Object> list(Integer page, Integer rows, String customerName) {
        page = page == 0 ? 1 : page;
        int offSet = (page - 1) * rows;

        List<Customer> customerList = customerDao.list(offSet, rows, customerName);
        HashMap<String, Object> map = new HashMap<>();
        map.put("rows", customerList);
        return map;
    }

    @Override
    public ServiceVO save(Customer customer) {
        //用户为空时可以新增，不为空就是修改
        if (customer.getCustomerId() == null) {
            Customer excustomer = customerDao.findCustomerByName(customer.getCustomerName());
            if (excustomer != null) {
                return new ServiceVO(ErrorCode.ACCOUNT_EXIST_CODE, ErrorCode.ACCOUNT_EXIST_MESS);
            }
            customerDao.addCustomer(customer);
            logService.save(new Log(Log.INSERT_ACTION, "添加客户" + customer.getCustomerName()));
        } else {
            customerDao.updateCustomer(customer);
            logService.save(new Log(Log.UPDATE_ACTION, "修改用户:" + customer.getCustomerName()));
        }
        return new ServiceVO<>(SuccessCode.SUCCESS_CODE, SuccessCode.SUCCESS_MESS);
    }

    @Override
    public ServiceVO delete(String ids) {
        String[] split = ids.split(",");
        for (String id : split) {
            customerDao.delete(Integer.parseInt(id));
        }
        return new ServiceVO(SuccessCode.SUCCESS_CODE,SuccessCode.SUCCESS_MESS);

    }

    @Override
    public List<Customer> getComboboxList(String q) {
        return customerDao.getCustomerListByNameLike(q);
    }
}
